<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 特定股票数据模型
 */
class Symbol extends CI_model {

	/**
	 * 创建公司财务信息表
	 */
	public function creatFinanceTableById($code) {
		// 载入数据库维护类:
		$this->load->dbforge();
		// 删除已有表
		$code = '`' . $code . '`';
		$this->dbforge->drop_table($code, true);
		// 创建字段
		$fields = array(
			's_id' => array(
				'type' => 'INT',
				'constraint' => 5,
				'unsigned' => TRUE,
				'auto_increment' => TRUE,
			),
			'jbmgsy' => array(
				'type' => 'decimal(10,2)',
				'null' => TRUE,
			),
			'jlr' => array(
				'type' => 'decimal(14,2)',
				'null' => TRUE,
			),
			'jlrzzl' => array(
				'type' => 'decimal(10,2)',
				'null' => TRUE,
			),
			'yyzsr' => array(
				'type' => 'decimal(14,2)',
				'null' => TRUE,
			),
			'yyzsrzzl' => array(
				'type' => 'decimal(10,2)',
				'null' => TRUE,
			),
			'jyxjllje' => array(
				'type' => 'decimal(14,2)',
				'null' => TRUE,
			),
			'tzxjllje' => array(
				'type' => 'decimal(14,2)',
				'null' => TRUE,
			),
			'czxjllje' => array(
				'type' => 'decimal(14,2)',
				'null' => TRUE,
			),
			'mgjzc' => array(
				'type' => 'decimal(10,2)',
				'null' => TRUE,
			),
			'xsmlv' => array(
				'type' => 'decimal(10,2)',
				'null' => TRUE,
			),
			'cwbbrq' => array(
				'type' => 'date',
			),
			'roe' => array(
				'type' => 'decimal(10,2)',
				'null' => TRUE,
			),
		);
		$this->dbforge->add_field($fields);
		// 创建主键
		$this->dbforge->add_key('s_id', TRUE);
		// 创建索引
		$this->dbforge->add_key('cwbbrq');
		// 创建索引
		$this->dbforge->add_key('roe');
		// 创建表
		$this->dbforge->create_table($code, TRUE);
	}

	/**
	 * 检查是否存在对应的公司财务数据表
	 */
	public function checkSymbolTable($scode = '') {
		// 取得所有表格列表
		$tables = $this->db->list_tables();
		// var_dump($tables);exit;
		return in_array($scode, $tables);
		// return $this->db->table_exists($scode);
	}

	/**
	 * 插入财务数据
	 */
	public function insertFinanceData(array $data, $code) {
		$code = '`' . $code . '`';
		$this->db->insert($code, $data);
	}

	/**
	 * 获取股票信息
	 */
	public function getStockInfoByCode($code) {
		$this->db->select('s_id, jbmgsy, jlr, jlrzzl, yyzsr, yyzsrzzl, jyxjllje, tzxjllje, czxjllje, mgjzc, xsmlv, cwbbrq, (jyxjllje / jlr) AS jlrhjl, (jyxjllje - tzxjllje) AS zyxjl');
		$code = '`' . $code . '`';
		return $this->db->get($code)->result_array();
	}

	/**
	 * 获取指定股票的营业收入同比增长率和净利润同比增长率数据
	 */
	public function getGrowthingData($symbol) {
		$symbol = '`' . $symbol . '`';
		return $this->db->order_by("cwbbrq", "desc")->get($symbol)->result_array();
	}

	// 获取指定股票的每股净资产
	public function getStockNetAssets($code) {
		$this->db->select('mgjzc');
		$code = '`' . $code . '`';
		return $this->db->get($code)->first_row('array');
	}

	/**
	 * 获取指定股票的最近5年营业收入同比增长率和净利润同比增长率数据
	 */
	public function getLastFiveData($symbol) {
		$symbol = '`' . $symbol . '`';
		return $this->db->order_by("cwbbrq", "desc")->limit(5)->get($symbol)->result_array();
	}

}
